package com.example.oasystem.controller.file;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.oasystem.config.ConstantProperties;
import com.example.oasystem.dao.file.AoaFileListDao;
import com.example.oasystem.dao.file.AoaFilePathDao;
import com.example.oasystem.entity.file.AoaFileList;
import com.example.oasystem.entity.file.AoaFilePath;
import com.example.oasystem.entity.user.AoaUser;
import com.example.oasystem.service.impl.FileManageServiceImpl;
import com.example.oasystem.utils.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class FileManagerController {

    @Autowired
    private AoaFilePathDao aoaFilePathDao;
    @Autowired
    private AoaFileListDao aoaFileListDao;
    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;
    @Autowired
    private ConstantProperties constantProperties;
    @Autowired
    FileManageServiceImpl fileManageService;
    @RequestMapping("/filemanage")
    public String filemanage(HttpSession session, Model model){
        AoaUser user = (AoaUser) session.getAttribute("user");
        AoaFilePath userrootpath = aoaFilePathDao.selectOne(new QueryWrapper<AoaFilePath>().eq("path_user_id", user.getUserId())
                .eq("parent_id",1L));
        //System.out.println("userrootpath = " + userrootpath);
        List<AoaFilePath> mcpaths = aoaFilePathDao.selectmcpaths(userrootpath.getPathId());
        //List<AoaFilePath> realmcpaths = aoaFilePathDao.selectAllChildPaths(userrootpath.getPathId());
        List<AoaFileList> files = aoaFileListDao.selectList(new QueryWrapper<AoaFileList>()
                .eq("path_id", userrootpath.getPathId()).or()
                .eq("file_isshare",1L)
                .ne("file_istrash",1L));
        List<AoaFilePath> allParentpaths = aoaFilePathDao.selectAllParentpaths(userrootpath.getPathId());
        // filemanage页面数据
        model.addAttribute("userrootpath",userrootpath);
        model.addAttribute("nowpath",userrootpath);
        model.addAttribute("mcpaths",mcpaths);
        // filetypeload页面数据
        model.addAttribute("files",files);
        model.addAttribute("userid",user.getUserId());
        model.addAttribute("paths",mcpaths);
        model.addAttribute("allparentpaths",allParentpaths);
        return "file/filemanage";
    }

    @RequestMapping("/filetest")
    public String filetest(HttpSession session,Model model,
                           @RequestParam String pathid){
        AoaFilePath nowpath = aoaFilePathDao.selectOne(new QueryWrapper<AoaFilePath>().eq("path_id", Long.parseLong(pathid)));
        List<AoaFilePath> allParentpaths = aoaFilePathDao.selectAllParentpaths(nowpath.getPathId());
        AoaUser user = (AoaUser) session.getAttribute("user");
        List<AoaFilePath> paths = aoaFilePathDao.selectmcpaths(nowpath.getPathId());
        AoaFilePath userrootpath = aoaFilePathDao.selectOne(new QueryWrapper<AoaFilePath>().eq("path_user_id", user.getUserId())
                .eq("parent_id",1L));
        List<AoaFilePath> mcpaths = aoaFilePathDao.selectmcpaths(userrootpath.getPathId());
        List<AoaFileList> files = aoaFileListDao.selectList(new QueryWrapper<AoaFileList>()
                .eq("path_id", nowpath.getPathId()).or()
                .eq("file_isshare",1L)
                .ne("file_istrash",1L));
        // filemanage页面数据
        model.addAttribute("userrootpath",userrootpath);
        model.addAttribute("mcpaths",mcpaths);
        // filetypeload页面数据
        model.addAttribute("paths",paths);
        model.addAttribute("nowpath",nowpath);
        model.addAttribute("allparentpaths",allParentpaths);
        model.addAttribute("files",files);
        model.addAttribute("userid",user.getUserId());
        return "file/filemanage";
    }

    // 文件上传
    @RequestMapping("/fileupload")
    public String fileupload(HttpSession session,Model model,
                             @RequestParam String pathid,
                             MultipartFile filePath){
        AoaUser user = (AoaUser)session.getAttribute("user");
        String uploadUrl = uploadFile(filePath);
        String s = uploadUrl.split("\\?")[0];
        int beginIndex = s.lastIndexOf("/");
        String attachmentName = s.substring(beginIndex+1);
        String fileShuffix = attachmentName.split("\\.")[1];

        AoaFileList aoaFileList = new AoaFileList();
        aoaFileList.setFileName(filePath.getOriginalFilename());
        aoaFileList.setFilePath(uploadUrl);
        aoaFileList.setFileShuffix(fileShuffix);
        aoaFileList.setContentType(filePath.getContentType());
        aoaFileList.setPathId(Long.parseLong(pathid));
        aoaFileList.setSize(filePath.getSize());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        aoaFileList.setUploadTime(sdf.format(new Date()));
        aoaFileList.setFileUserId(user.getUserId());
        aoaFileList.setFileIstrash(0L);
        aoaFileList.setFileIsshare(0L);

        aoaFileListDao.insert(aoaFileList);

        return "forward:/filetest?pathid" + pathid;
    }

    @RequestMapping("/mcloadpath")
    public String mcloadpath(Model model,@RequestParam String mctoid){
        List<AoaFilePath> mcpaths = aoaFilePathDao.selectmcpaths(Long.parseLong(mctoid));
        model.addAttribute("mcpaths",mcpaths);
        return "file/mcpathload";
    }

    //文档分类
    @RequestMapping("/filetypedocument")
    public String filetypedocument(HttpSession session,Model model){
        AoaUser user = (AoaUser)session.getAttribute("user");
        AoaFilePath userrootpath = aoaFilePathDao.selectOne(new QueryWrapper<AoaFilePath>().eq("path_user_id", user.getUserId())
                .eq("parent_id",1L));
        List<AoaFilePath> mcpaths = aoaFilePathDao.selectmcpaths(userrootpath.getPathId());

        System.out.println("111111userrootpath = " + userrootpath);
        List<AoaFileList> files = aoaFileListDao.selectAllDocument(userrootpath.getPathId());

        // filemanage页面数据
        model.addAttribute("userrootpath",userrootpath);
        model.addAttribute("nowpath",userrootpath);
        model.addAttribute("mcpaths",mcpaths);

        // filetypeload页面数据
        model.addAttribute("files",files);
        model.addAttribute("userid",user.getUserId());

        model.addAttribute("isload",true);
        model.addAttribute("type","document");
        return "file/filemanage";
    }

    // 图片分类
    @RequestMapping("/filetypeimage")
    public String filetypeimage(HttpSession session,Model model){
        AoaUser user = (AoaUser)session.getAttribute("user");
        AoaFilePath userrootpath = aoaFilePathDao.selectOne(new QueryWrapper<AoaFilePath>().eq("path_user_id", user.getUserId())
                .eq("parent_id",1L));
        List<AoaFilePath> mcpaths = aoaFilePathDao.selectmcpaths(userrootpath.getPathId());
        List<AoaFileList> files = aoaFileListDao.selectAllImages(userrootpath.getPathId());
        // filemanage页面数据
        model.addAttribute("userrootpath",userrootpath);
        model.addAttribute("nowpath",userrootpath);
        model.addAttribute("mcpaths",mcpaths);

        // filetypeload页面数据
        model.addAttribute("files",files);
        model.addAttribute("userid",user.getUserId());

        model.addAttribute("isload",true);
        model.addAttribute("type","picture");
        return "file/filemanage";
    }


    // 音乐分类
    @RequestMapping("/filetypemusic")
    public String filetypemusic(HttpSession session,Model model){
        AoaUser user = (AoaUser)session.getAttribute("user");
        AoaFilePath userrootpath = aoaFilePathDao.selectOne(new QueryWrapper<AoaFilePath>().eq("path_user_id", user.getUserId())
                .eq("parent_id",1L));
        List<AoaFilePath> mcpaths = aoaFilePathDao.selectmcpaths(userrootpath.getPathId());
        List<AoaFileList> files = aoaFileListDao.selectAllMusic(userrootpath.getPathId());
        // filemanage页面数据
        model.addAttribute("userrootpath",userrootpath);
        model.addAttribute("nowpath",userrootpath);
        model.addAttribute("mcpaths",mcpaths);

        // filetypeload页面数据
        model.addAttribute("files",files);
        model.addAttribute("userid",user.getUserId());

        model.addAttribute("isload",true);
        model.addAttribute("type","music");
        return "file/filemanage";
    }


    // 分享文件
    @RequestMapping("/doshare")
    public String doshare(Model model,
                          @RequestParam String pathid,
                          @RequestParam List<Long> checkfileids){
        if(!checkfileids.isEmpty()){
            for (Long checkfileid : checkfileids) {
                AoaFileList share = new AoaFileList();
                share.setFileId(checkfileid);
                share.setFileIsshare(1L);
                aoaFileListDao.updateById(share);
            }
        }
        model.addAttribute("message","分享成功");
        model.addAttribute("pathid",pathid);
        return "forward:/filetest";
    }


    @RequestMapping("downfile")
    public void downFile(@RequestParam("fileid") int fileid, HttpServletResponse response) {
        AoaFileList file=aoaFileListDao.selectOneFlist(fileid);
        String str=file.getFilePath();
        String path1=str.substring(48);
        String[] path2=path1.split("\\?");
        AliyunOSSUtil.download(path2[0],response);
    }


    @RequestMapping("deletefile")
    public String deletefile(HttpSession session,
                             @RequestParam("pathid") Long pathid,
                             @RequestParam("checkpathids") List<Long> checkpathids,
                             @RequestParam("checkfileids") List<Long> checkfileids, Model model) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        if (!checkfileids.isEmpty()) {
            //文件放入回收站
            for (Long checkfileid : checkfileids) {
                AoaFileList deleteFile = new AoaFileList();
                deleteFile.setFileId(checkfileid);
                deleteFile.setFileIstrash(1L);
                aoaFileListDao.updateById(deleteFile);
            }
        }
        if (!checkpathids.isEmpty()) {
            System.out.println("checkpathids = " + checkpathids);
            for (Long checkpathid : checkpathids) {
                List<AoaFilePath> allChildPaths = aoaFilePathDao.selectAllChildPaths(checkpathid);
                System.out.println("allChildPaths = " + allChildPaths);
                // 把文件夹中 所有子文件夹 放入回收站
                for (AoaFilePath childPath : allChildPaths) {
                    AoaFilePath deletePath = new AoaFilePath();
                    deletePath.setPathId(childPath.getPathId());
                    deletePath.setPathIstrash(1L);
                    aoaFilePathDao.updateById(deletePath);
                    // 把文件夹中 所有子文件夹中 所有文件 放入回收站
                    List<AoaFileList> deletePathFiles = aoaFileListDao.selectList(new QueryWrapper<AoaFileList>().eq("path_id", childPath.getPathId()));
                    for (AoaFileList deletePathFile : deletePathFiles) {
                        AoaFileList deleteFile = new AoaFileList();
                        deleteFile.setFileId(deletePathFile.getFileId());
                        deleteFile.setFileIstrash(1L);
                        aoaFileListDao.updateById(deleteFile);
                    }
                }
            }
        }
        model.addAttribute("pathid", pathid);
        return "forward:/filetest";
    }

    //新建文件夹
    @RequestMapping("/createpath")
    public String createpath(HttpSession session,Model model,
                             @RequestParam("pathid") Long pathid,
                             @RequestParam("pathname") String pathname){
        AoaUser user = (AoaUser)session.getAttribute("user");
        AoaFilePath aoaFilePath = new AoaFilePath();
        aoaFilePath.setParentId(pathid);
        aoaFilePath.setPathName(pathname);
        aoaFilePath.setPathUserId(user.getUserId());
        aoaFilePath.setPathIstrash(0L);
        aoaFilePathDao.insert(aoaFilePath);
        model.addAttribute("pathid",pathid);
        model.addAttribute("message","修改成功");
        return "forward:/filetest";
    }



    // 文件上传封装方法
    public String uploadFile(MultipartFile filePath) {
        String uploadUrl = null;
        try {
            if(null != filePath){
                String filename = filePath.getOriginalFilename();
                if(!"".equals(filename.trim())){
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(filePath.getBytes());
                    os.close();
                    filePath.transferTo(newFile);
                    //上传到OSS
                    uploadUrl = constantProperties.getHead() + aliyunOSSUtil.upload(newFile) + constantProperties.getEnd();
                }
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        return uploadUrl;
    }

    // 重命名
    @RequestMapping("rename")
    public String rename(@RequestParam("name") String name,HttpSession session,
                         @RequestParam("renamefp") Integer renamefp,
                         @RequestParam("pathid") Integer pathid,
                         @RequestParam("isfile") boolean isfile,
                         Model model){

        //这里调用重命名方法
        AoaUser user = (AoaUser) session.getAttribute("user");
        fileManageService.rename(name, renamefp, pathid, isfile,user);
        model.addAttribute("pathid", pathid);
        return "forward:/filetest";
    }

    /**
     * 移动和复制
     * @param mctoid
     * @param model
     * @return
     */
    @RequestMapping("mcto")
    public String mcto(HttpSession session,
                       @RequestParam("morc") boolean morc,
                       @RequestParam("mctoid") Long mctoid,
                       @RequestParam("pathid") Long pathid,
                       @RequestParam("mcfileids")List<Long> mcfileids,
                       @RequestParam("mcpathids")List<Long> mcpathids,
                       Model model){
//        System.out.println("--------------------");
//        System.out.println("mcfileids "+mcfileids);//145
//        System.out.println("mcpathids "+mcpathids);//[]
//        System.out.println("morc "+morc);//true
//        System.out.println("mctoid "+mctoid);//6
//        System.out.println("pathid "+pathid);//94

        if(morc){
            //移动选择的所有文件夹和文件

            //移动选择得所有文件
            AoaFileList aoaFileList = new AoaFileList();
            aoaFileList.setPathId(mctoid);
            for (Long mcfileid : mcfileids) {
                aoaFileList.setFileId(mcfileid);
                aoaFileListDao.updateById(aoaFileList);
            }

            //移动选择的所有文件夹
            AoaFilePath aoaFilePath = new AoaFilePath();
            aoaFilePath.setParentId(mctoid);
            for (Long mcpathid : mcpathids) {
                if(mcpathid==mctoid.longValue()){
                    //非人类操作，文件夹移动到自己的文件夹下面

                }else {
                    aoaFilePath.setPathId(mcpathid);
                    aoaFilePathDao.updateById(aoaFilePath);
                }
            }
        }else {
            //复制选择的所有文件夹和文件
            //复制选择得所有文件
            for (Long mcfileid : mcfileids) {
                AoaFileList aoaFileList = aoaFileListDao.selectById(mcfileid);
                aoaFileList.setPathId(mctoid);
                aoaFileListDao.insert(aoaFileList);
            }

            //复制选择的所有文件夹

            for (Long mcpathid : mcpathids) {
                if(mcpathid==mctoid.longValue()){
                    //非人类操作，文件夹复制到自己的文件夹下面

                }else {
                    AoaFilePath aoaFilePath = aoaFilePathDao.selectById(mcpathid);
                    aoaFilePath.setParentId(mctoid);
                    aoaFilePathDao.insert(aoaFilePath);
                }
            }
        }
        model.addAttribute("pathid", pathid);
        return "forward:/filetest";
    }


    @PostMapping("fileloadtrashfile")
    public String fileloadtrashfile(Model model,String type,
                                    @RequestParam(value = "checkfileids[]",required = false) Long[] checkfileids,
                                    @RequestParam(value = "checkpathids[]",required = false) Long[] checkpathids){
        //System.out.println(Arrays.toString(checkfileids));
        if(checkfileids != null){
            AoaFileList aoaFileList = new AoaFileList();
            aoaFileList.setFileIstrash(1L);
            //分类后文件放入回收站
            for (Long checkfileid : checkfileids) {
                aoaFileList.setFileId(checkfileid);
                aoaFileListDao.updateById(aoaFileList);
            }
        }
        if(checkpathids!=null){
            for (Long checkpathid : checkpathids) {
                List<AoaFilePath> allChildPaths = aoaFilePathDao.selectAllChildPaths(checkpathid);
                //System.out.println("allChildPaths = " + allChildPaths);
                // 把文件夹中 所有子文件夹 放入回收站
                for (AoaFilePath childPath : allChildPaths) {
                    AoaFilePath deletePath = new AoaFilePath();
                    deletePath.setPathId(childPath.getPathId());
                    deletePath.setPathIstrash(1L);
                    aoaFilePathDao.updateById(deletePath);
                    // 把文件夹中 所有子文件夹中 所有文件 放入回收站
                    List<AoaFileList> deletePathFiles = aoaFileListDao.selectList(new QueryWrapper<AoaFileList>().eq("path_id", childPath.getPathId()));
                    for (AoaFileList deletePathFile : deletePathFiles) {
                        AoaFileList deleteFile = new AoaFileList();
                        deleteFile.setFileId(deletePathFile.getFileId());
                        deleteFile.setFileIstrash(1L);
                        aoaFileListDao.updateById(deleteFile);
                    }
                }
            }
        }


        model.addAttribute("type",type);
        return "forward:filetypeload";
    }

    @PostMapping("fileloaddeletefile")
    public String fileloaddeletefile(Model model,String type,
                                     @RequestParam(value = "checkfileids[]",required = false) Long[] checkfileids,
                                     @RequestParam(value = "checkpathids[]",required = false) Long[] checkpathids){
        if(checkfileids!=null){
            for (Long checkfileid : checkfileids) {
                aoaFileListDao.deleteById(checkfileid);
            }
        }
        if(checkpathids!=null){
            for (Long checkpathid : checkpathids) {
                List<AoaFilePath> allChildPaths = aoaFilePathDao.selectAllChildPaths(checkpathid);
                System.out.println("allChildPaths = " + allChildPaths);
                // 把文件夹中 所有子文件夹 删除（包括自己）
                for (AoaFilePath childPath : allChildPaths) {
                    aoaFilePathDao.deleteById(childPath.getPathId());
                    // 把文件夹中 所有子文件夹中 所有文件 删除（包括自己的所有文件）
                }
            }
        }
        model.addAttribute("type",type);
        return "forward:filetypeload";
    }



    @PostMapping("findfileandpath")
    public String findfileandpath(HttpSession session,
                                  String findfileandpath, Model model){
        AoaUser user = (AoaUser) session.getAttribute("user");
        AoaFilePath userrootpath = aoaFilePathDao.selectOne(new QueryWrapper<AoaFilePath>().eq("path_user_id", user.getUserId())
                .eq("parent_id",1L));
        List<AoaFilePath> mcpaths = aoaFilePathDao.selectmcpaths(userrootpath.getPathId());

        List<AoaFileList> files = aoaFileListDao.selectList(new QueryWrapper<AoaFileList>().eq("path_id", userrootpath.getPathId())
                .ne("file_istrash",1L));
        List<AoaFilePath> allParentpaths = aoaFilePathDao.selectAllParentpaths(userrootpath.getPathId());
        // filemanage页面数据
        model.addAttribute("userrootpath",userrootpath);
        model.addAttribute("nowpath",userrootpath);
        model.addAttribute("mcpaths",mcpaths);
        // filetypeload页面数据
        model.addAttribute("files",files);
        model.addAttribute("userid",user.getUserId());
        model.addAttribute("paths",mcpaths);
        model.addAttribute("allparentpaths",allParentpaths);



        model.addAttribute("isshare",null);
        model.addAttribute("istrash",null);
        return "forward:filemanage";
    }


}
